using System;
using System.Collections.Generic;
using System.Linq;
using C3.Proto.Core.Model;
using C3.Proto.Core.Repository;
using C3.Proto.Core.Service;
using log4net;

namespace C3.Proto.Core
{
    public class SafetyService : ISafetyService
    {
        public SafetyService(ISafetyRepo safetyRepo)
        {
            SafetyRepo = safetyRepo;
            Categories = new string[]
                                 {
                                     "Confined Space",
                                     "Cranes And Hoisting Equipment",
                                     "Electrical",
                                     "Excavation",
                                     "Fall Protection",
                                     "Fire Prevention & Suppression",
                                     "Fire Protection",
                                     "General Work Activities",
                                     "Ground Supported Scaffold Installation / Use",
                                     "Housekeeping",
                                     "Ladder Usage",
                                     "Ladders",
                                     "Motorized Equipment",
                                     "No Value",
                                     "P.P.E.",
                                     "Project Oversight",
                                     "Scissor & Aerial Lift Operation",
                                     "Scissor / Arial Lifts",
                                     "Suspended Scaffold Installation & Use",
                                     "Tools - Hand, Power & Powder Shot",
                                     "Welding & Cutting Operations",
                                     "Welding / Flame Cutting"
                                 };
            GCCategories = new string[]
                               {
                                   "Adequate lighting provided for task",
                                   "Clearance from surrounding hazard(s) maintained",
                                   "Construction waste properly controlled and disposed of",
                                   "Environmental hazard(s) identified and controlled",
                                   "Equipment in use inspected, maintained, and used as required",
                                   "Fall protection plan provided as needed",
                                   "Fire prevention and suppression provided",
                                   "Issue(s) not currently identified in this section",
                                   "JHA(s) developed and communicated to all workers",
                                   "Measures provided to protect other workers in area",
                                   "No unauthorized modification of equipment",
                                   "No visible damage to equipment",
                                   "Permit issued and posted in immediate work area as needed",
                                   "Plan to protect workers from recognized hazard(s)",
                                   "Proper containers for storage and handling of materials",
                                   "Proper use of equipment as intended",
                                   "Qualified equipment operator(s) provided as needed",
                                   "Supervision present during activities",
                                   "Tool guards and safety features provided and maintained on all tools",
                                   "Trip/slip hazards controlled",
                                   "Work area clear and unobstructed",
                                   "Work area properly secured from unauthorized access",
                                   "Worker(s) trained for proper equipment use",
                                   "Worker(s) trained for task",
                                   "Worker(s) using fall protection as required",
                                   "Worker(s) with proper PPE for activities"
                               };
            Injuries = new string[]
                           {
                               "ALL OTHER SPECIFIC INJURIES NOC",
                               "ANGINA PECTORIS (CONDITION ASSOC W/HEART DISEASE)",
                               "BURN",
                               "CONCUSSION",
                               "CONTUSION",
                               "CRUSHING",
                               "DERMATITIS",
                               "DISLOCATION",
                               "ELECTRIC SHOCK",
                               "FOREIGN BODY",
                               "FRACTURE",
                               "HEARING LOSS OR IMPAIRMENT",
                               "HEAT PROSTRATION",
                               "HERNIA",
                               "INFECTION",
                               "INFLAMMATION",
                               "LACERATION",
                               "NO PHYSICAL INJURY",
                               "PUNCTURE",
                               "RESPIRATORY DISORDERS",
                               "RUPTURE",
                               "SEVERANCE",
                               "SPRAIN",
                               "STRAIN",
                               "SYNCOPE"
                           };
        }

        protected string[] Injuries
        {
            get; set;
        }

        protected string[] Categories
        {
            get; set;
        }

        protected string[] GCCategories
        {
            get;
            set;
        }

        private static readonly ILog Log = LogManager.GetLogger(typeof(SafetyService));
        protected ISafetyRepo SafetyRepo
        {
            get; set;
        }

        //public ProjectResults GetProjectInspections(string project, DateTime start, DateTime end)
        //{ 
            
        //    try
        //    {
        //        //get all inspections for the date range
        //        var inspections = SafetyRepo.GetMonthlyInspections(start, end).Where(t=>t.projectJobNumber == project).ToList();
        //        var claims = SafetyRepo.GetClaims(start, end).Where(t => t.SiteLevel1 == project).ToList();
               
        //        var results = new ProjectResults
        //                         {
        //                             GC = new List<MonthlyTotal>(),
        //                             ROCIP = new List<MonthlyTotal>(),
        //                             OFPC = new List<MonthlyTotal>(),
        //                             Steps = SafetyRepo.GetSteps(start, end).Where(t => t.ProjectId == project).ToList(),
        //                             Claims = new List<MonthlyClaim>()
        //                         };

        //        //iterate by month
        //        while (end > start)
        //        {
        //            //ToUpper is required here

        //            var gc = inspections.Where(t => t.inspectorLastName.ToUpper().Contains("(GC)") && t.inspectionDate >= start && t.inspectionDate < start.AddMonths(1)).ToList();

        //            var rocip = inspections.Where(t => t.inspectorLastName.ToUpper().Contains("(ROCIP)") && t.inspectionDate >= start && t.inspectionDate < start.AddMonths(1)).ToList();

        //            var ofpc = inspections.Where(t => t.inspectorLastName.ToUpper().Contains("(OFPC)") && t.inspectionDate >= start && t.inspectionDate < start.AddMonths(1)).ToList();

        //            //use distinct to get actual inspection count
        //            var monthcount = (from m in gc select m.inspectionID).Distinct().ToList();
        //            var month = string.Format("{0} {1}",start.ToString("MMMM"),start.ToString("YYYY"));
        //            results.GC.Add(new MonthlyTotal(){ Name = month, Total = monthcount.Count});

        //            monthcount = (from m in rocip select m.inspectionID).Distinct().ToList();
        //            month = string.Format("{0} {1}", start.ToString("MMMM"), start.ToString("YYYY"));
        //            results.ROCIP.Add(new MonthlyTotal() { Name = month, Total = monthcount.Count });

        //            monthcount = (from m in ofpc select m.inspectionID).Distinct().ToList();
        //            month = string.Format("{0} {1}", start.ToString("MMMM"), start.ToString("YYYY"));
        //            results.OFPC.Add(new MonthlyTotal() { Name = month, Total = monthcount.Count });
                    
        //            //Monthly claim total
        //            var amount = claims.Where(t => t.DateofLoss >= start && t.DateofLoss < start.AddMonths(1)).Sum(
        //                t => t.NetIncurredTotal);
        //            //Monthly claims
        //            var count =
        //                claims.Where(t => t.DateofLoss >= start && t.DateofLoss < start.AddMonths(1)).ToList().Count;
        //            results.Claims.Add(new MonthlyClaim()
        //                                   {
        //                                       Amount = amount,
        //                                       Count = count
        //                                   });


        //            results.GCSeverityA = gc.Where(t => t.severityLifeThreatCount == 1).ToList().Count;
        //            results.GCSeverityB = gc.Where(t => t.severityHighCount == 1).ToList().Count;
        //            results.GCSeverityC = gc.Where(t => t.severityMediumCount == 1).ToList().Count;
        //            results.GCSeverityD = gc.Where(t => t.severityLowCount == 1).ToList().Count;

        //            results.OFPCSeverityA = ofpc.Where(t => t.severityLifeThreatCount == 1).ToList().Count;
        //            results.OFPCSeverityB = ofpc.Where(t => t.severityHighCount == 1).ToList().Count;
        //            results.OFPCSeverityC = ofpc.Where(t => t.severityMediumCount == 1).ToList().Count;
        //            results.OFPCSeverityD = ofpc.Where(t => t.severityLowCount == 1).ToList().Count;

        //            results.ROCIPSeverityA = rocip.Where(t => t.severityLifeThreatCount == 1).ToList().Count;
        //            results.ROCIPSeverityB = rocip.Where(t => t.severityHighCount == 1).ToList().Count;
        //            results.ROCIPSeverityC = rocip.Where(t => t.severityMediumCount == 1).ToList().Count;
        //            results.ROCIPSeverityD = rocip.Where(t => t.severityLowCount == 1).ToList().Count;

        //            //increment the month
        //            start = start.AddMonths(1);


                    
        //        }
                
        //        return results;
        //    }catch(Exception ex)
        //    {
        //        Log.Error(ex);
        //        return null;
        //    }
        //}
        public ProjectResults GetProjectInspections(string project, DateTime start, DateTime end)
        {

            try
            {
                //get all inspections for the date range
                var inspections = SafetyRepo.GetMonthlyInspectionSummaries(start, end).Where(t => t.projectJobNumber == project).ToList();
                var claims = SafetyRepo.GetClaims(start, end).Where(t => t.SiteLevel1.Trim() == project).ToList();
                

                if (inspections.Count == 0)
                {
                    return null;
                }

                var results = new ProjectResults
                {
                    
                    GC = new List<MonthlyTotal>(),
                    ROCIP = new List<MonthlyTotal>(),
                    OFPC = new List<MonthlyTotal>(),
                    Steps = SafetyRepo.GetSteps(project, start, end),
                    ManHours = SafetyRepo.GetManHours(project, start, end),
                    RIR = SafetyRepo.GetRIR(project, start, end),
                    Labor = SafetyRepo.GetLabor(project, start,end),
                    Claims = new List<MonthlyClaim>(),
                    GCB = new List<BiMonthlyTotal>(),
                    OFPCB = new List<BiMonthlyTotal>(),
                    ROCIPB = new List<BiMonthlyTotal>()
                };

                
                results.Project = inspections[0].projectTitle;
                var y = SafetyRepo.GetClaims(new DateTime(2008, 1, 1), new DateTime(2011, 12, 31)).Where(t => t.SiteLevel1.Trim() == project).ToList();
                var y1 = SafetyRepo.GetClaims(new DateTime(2012, 1, 1), new DateTime(2012, 12, 31)).Where(t => t.SiteLevel1.Trim() == project).ToList();
                var y2 = SafetyRepo.GetClaims(new DateTime(2013, 1, 1), new DateTime(2013, 12, 31)).Where(t => t.SiteLevel1.Trim() == project).ToList();

                results.YearTotal = (y.Count == 0) ? 0.00 : Math.Round(y.Sum(t => t.NetIncurredTotal), 0);
                results.YearTotal1 = (y1.Count == 0) ? 0.00 : Math.Round(y1.Sum(t=>t.NetIncurredTotal),0);
                results.YearTotal2 = (y2.Count == 0) ? 0.00 : Math.Round(y2.Sum(t => t.NetIncurredTotal), 0);

                results.YearCount = (y.Count == 0) ? 0 : y.Count;
                results.YearCount1 = (y1.Count == 0) ? 0 : y1.Count;
                results.YearCount2 = (y2.Count == 0) ? 0 : y2.Count;
                
                 
                //iterate by month
                while (end > start)
                {
                    //ToUpper is required here


                    var gc = inspections.Where(t => t.inspectorLastName.ToUpper().Contains("(GC)") && t.inspectionDate >= start && t.inspectionDate < start.AddMonths(1)).ToList();

                    var rocip = inspections.Where(t => t.inspectorLastName.ToUpper().Contains("(ROCIP)") && t.inspectionDate >= start && t.inspectionDate < start.AddMonths(1)).ToList();

                    var ofpc = inspections.Where(t => t.inspectorLastName.ToUpper().Contains("(OFPC)") && t.inspectionDate >= start && t.inspectionDate < start.AddMonths(1)).ToList();
                    ofpc.AddRange(inspections.Where(t => t.inspectorLastName.ToUpper().Contains("(MDA)") && t.inspectionDate >= start && t.inspectionDate < start.AddMonths(1)).ToList());
                    ofpc.AddRange(inspections.Where(t => t.inspectorLastName.ToUpper().Contains("(UTSWMC)") && t.inspectionDate >= start && t.inspectionDate < start.AddMonths(1)).ToList());

                    

                    //use distinct to get actual inspection count
                    //var monthcount = (from m in gc select m.inspectionID).Distinct().ToList();
                    var month = string.Format("{0}-{1}", start.ToString("MMMM"), start.ToString("yy"));
                    
                   

                    results.GC.Add(new MonthlyTotal()
                                       {
                                           Name = month, Total = gc.Count
                                           
                                       });

                    //monthcount = (from m in rocip select m.inspectionID).Distinct().ToList();
                    //month = string.Format("{0}-{1}", start.ToString("MMMM"), start.ToString("YY"));
                    results.ROCIP.Add(new MonthlyTotal()
                                          {
                                              Name = month, Total = rocip.Count
                                              
                                          });

                    //monthcount = (from m in ofpc select m.inspectionID).Distinct().ToList();
                    //month = string.Format("{0} {1}", start.ToString("MMMM"), start.ToString("YYYY"));
                    results.OFPC.Add(new MonthlyTotal()
                                         {
                                             Name = month, Total = ofpc.Count
                                             
                                         });

                    //Monthly claim total
                    var amount = claims.Where(t => t.DateofLoss >= start && t.DateofLoss < start.AddMonths(1)).Sum(
                        t => t.NetIncurredTotal);
                    //Monthly claims
                    var count =
                        claims.Where(t => t.DateofLoss >= start && t.DateofLoss < start.AddMonths(1)).ToList().Count;
                    results.Claims.Add(new MonthlyClaim()
                    {
                        Amount = amount,
                        Count = count
                    });

                    var year = start.ToString("yy");
                    //First 15 days of the month
                    var b = gc.Where(t => t.inspectionDate <= start.AddDays(15)).ToList();
                    var life = b.Sum(t => t.severityLifeThreatCount) * 16;
                    var high = b.Sum(t => t.severityHighCount) * 12;
                    var med = b.Sum(t => t.severityMediumCount) * 8;
                    var low = b.Sum(t => t.severityLowCount) * 4;
                    results.GCB.Add(new BiMonthlyTotal()
                    {
                        Total = life + high + med + low,
                        Name = string.Format("{0}-{1}", start.ToString("MMM"), year)

                    });
                    //Last 15 days of the month
                    b = gc.Where(t => t.inspectionDate > start.AddDays(15)).ToList();
                    life = b.Sum(t => t.severityLifeThreatCount) * 16;
                    high = b.Sum(t => t.severityHighCount) * 12;
                    med = b.Sum(t => t.severityMediumCount) * 8;
                    low = b.Sum(t => t.severityLowCount) * 4;
                    results.GCB.Add(new BiMonthlyTotal()
                    {
                        Total = life + high + med + low,
                        Name = string.Format("{0}-{1}", start.ToString("MMM"), year)

                    });

                    b = ofpc.Where(t => t.inspectionDate <= start.AddDays(15)).ToList();
                    life = b.Sum(t => t.severityLifeThreatCount) * 16;
                    high = b.Sum(t => t.severityHighCount) * 12;
                    med = b.Sum(t => t.severityMediumCount) * 8;
                    low = b.Sum(t => t.severityLowCount) * 4;
                    results.OFPCB.Add(new BiMonthlyTotal()
                                          {
                                              Total = life + high + med + low,
                                              Name = string.Format("{0}-{1}", start.ToString("MMM"), year)
                                              
                                          });

                    b = ofpc.Where(t => t.inspectionDate > start.AddDays(15)).ToList();
                    life = b.Sum(t => t.severityLifeThreatCount) * 16;
                    high = b.Sum(t => t.severityHighCount) * 12;
                    med = b.Sum(t => t.severityMediumCount) * 8;
                    low = b.Sum(t => t.severityLowCount) * 4;
                    results.OFPCB.Add(new BiMonthlyTotal()
                                          {
                                              Total = life + high + med + low,
                                              Name = string.Format("{0}-{1}", start.ToString("MMM"), year)
                                              
                                          });

                    b = rocip.Where(t => t.inspectionDate <= start.AddDays(15)).ToList();
                     life = b.Sum(t => t.severityLifeThreatCount) * 16;
                     high = b.Sum(t => t.severityHighCount) * 12;
                     med = b.Sum(t => t.severityMediumCount) * 8;
                     low = b.Sum(t => t.severityLowCount) * 4;
                     results.ROCIPB.Add(new BiMonthlyTotal()
                     {
                         Total = life + high + med + low,
                         Name = string.Format("{0}-{1}", start.ToString("MMM"), year)

                     });

                     b = rocip.Where(t => t.inspectionDate > start.AddDays(15)).ToList();
                    life = b.Sum(t => t.severityLifeThreatCount) * 16;
                    high = b.Sum(t => t.severityHighCount) * 12;
                    med = b.Sum(t => t.severityMediumCount) * 8;
                    low = b.Sum(t => t.severityLowCount) * 4;
                    results.ROCIPB.Add(new BiMonthlyTotal()
                     {
                         Total = life + high + med + low,
                         Name = string.Format("{0}-{1}", start.ToString("MMM"), year)

                     });
                    


                    //increment the month
                    start = start.AddMonths(1);



                }
                var g = inspections.Where(t => t.inspectionDate >= end.AddMonths(-1) && t.inspectorLastName.ToUpper().Contains("(GC)"));

                var r = inspections.Where(t => t.inspectionDate >= end.AddMonths(-1) && t.inspectorLastName.ToUpper().Contains("(ROCIP)"));

                var o = inspections.Where(t => t.inspectionDate >= end.AddMonths(-1) && t.inspectorLastName.ToUpper().Contains("(OFPC)")).ToList();
                o.AddRange(inspections.Where(t => t.inspectorLastName.ToUpper().Contains("(MDA)") && t.inspectionDate >= end.AddMonths(-1)).ToList());
                o.AddRange(inspections.Where(t => t.inspectorLastName.ToUpper().Contains("(UTSWMC)") && t.inspectionDate >= end.AddMonths(-1)).ToList());

                results.GCSeverityA = g.Sum(t => t.severityLifeThreatCount);
                results.GCSeverityB = g.Sum(t => t.severityHighCount);
                results.GCSeverityC = g.Sum(t => t.severityMediumCount);
                results.GCSeverityD = g.Sum(t => t.severityLowCount);

                results.OFPCSeverityA = o.Sum(t => t.severityLifeThreatCount);
                results.OFPCSeverityB = o.Sum(t => t.severityHighCount);
                results.OFPCSeverityC = o.Sum(t => t.severityMediumCount);
                results.OFPCSeverityD = o.Sum(t => t.severityLowCount);

                results.ROCIPSeverityA = r.Sum(t => t.severityLifeThreatCount);
                results.ROCIPSeverityB = r.Sum(t => t.severityHighCount);
                results.ROCIPSeverityC = r.Sum(t => t.severityMediumCount);
                results.ROCIPSeverityD = r.Sum(t => t.severityLowCount);
                
                return results;
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return null;
            }
        }
        public StateResults GetStateReults(DateTime start, DateTime end)
        {

            try
            {
                var results = new StateResults()
                {
                    CategoryDeficiencies = new List<Deficiencies>(),
                    GeneralDeficiencies = new List<Deficiencies>(),
                    Claims = new List<Claim>(),
                    Injuries = new Dictionary<string, int>(),
                    Accidents = new Dictionary<string, int>()

                };

                //GC

                var i = SafetyRepo.GetMonthlyInspections(start, end);

                var gc = i.Where(t => t.inspectorLastName.ToUpper().Contains("(GC)")).ToList();

                var rocip = i.Where(t => t.inspectorLastName.ToUpper().Contains("(ROCIP)")).ToList();

                var ofpc = i.Where(t => t.inspectorLastName.ToUpper().Contains("(OFPC)")).ToList();
                ofpc.AddRange(i.Where(t => t.inspectorLastName.ToUpper().Contains("(MDA)")).ToList());
                ofpc.AddRange(i.Where(t => t.inspectorLastName.ToUpper().Contains("(UTSWMC)")).ToList());

                var monthcount = (from m in gc select m.inspectionID).Distinct().ToList();
                var projectcount = (from m in gc select m.projectID).Distinct().ToList();
                results.GCCount = monthcount.Count;
                results.GCProjects = projectcount.Count;

                monthcount = (from m in rocip select m.inspectionID).Distinct().ToList();
                projectcount = (from m in rocip select m.projectID).Distinct().ToList();
                results.ROCIPCount = monthcount.Count;
                results.ROCIPProjects = projectcount.Count;

                monthcount = (from m in ofpc select m.inspectionID).Distinct().ToList();
                projectcount = (from m in ofpc select m.projectID).Distinct().ToList();
                results.OFPCCount = monthcount.Count;
                results.OFPCProjects = projectcount.Count;

                //Get category percentages
                double gcunsafes = gc.Sum(t => t.unsafeObservationCount);
                double rocipunsafes = rocip.Sum(t => t.unsafeObservationCount);
                double ofpcunsafes = ofpc.Sum(t => t.unsafeObservationCount);
                foreach (var c in Categories)
                {

                    double g =
                        gc.Where(t => t.unsafeObservationCount > 0 && t.categoryName == c).Sum(
                            t => t.unsafeObservationCount);

                    double r =
                        rocip.Where(t => t.unsafeObservationCount > 0 && t.categoryName == c).Sum(
                            t => t.unsafeObservationCount);

                    double o =
                        ofpc.Where(t => t.unsafeObservationCount > 0 && t.categoryName == c).Sum(
                            t => t.unsafeObservationCount);


                    //Dont add empty datasets
                    if (g == 0 && r == 0 && o == 0) continue;
                    var d = new Deficiencies()
                        {
                            Category = c
                        };
                    if (gcunsafes > 0)
                        d.GC = Math.Round((g / gcunsafes) * 100, 3, MidpointRounding.AwayFromZero);
                    
                    if (ofpcunsafes > 0)
                        d.OFPC = Math.Round((o / ofpcunsafes) * 100, 3, MidpointRounding.AwayFromZero);
                    if (rocipunsafes > 0)
                        d.ROCIP = Math.Round((r / rocipunsafes) * 100, 3, MidpointRounding.AwayFromZero);

                
                    results.CategoryDeficiencies.Add(d);

                }
                //Get deficiencies for the subcategories under GC
                gcunsafes = gc.Where(t => t.categoryName == "General Work Activities").Sum(t => t.unsafeObservationCount);
                rocipunsafes = rocip.Where(t => t.categoryName == "General Work Activities").Sum(t => t.unsafeObservationCount);
                ofpcunsafes = ofpc.Where(t => t.categoryName == "General Work Activities").Sum(t => t.unsafeObservationCount);
                foreach (var c in GCCategories)
                {

                    double g =
                        gc.Where(t => t.unsafeObservationCount > 0 && t.subCategoryName == c).Sum(
                            t => t.unsafeObservationCount);

                    double r =
                        rocip.Where(t => t.unsafeObservationCount > 0 && t.subCategoryName == c).Sum(
                            t => t.unsafeObservationCount);

                    double o =
                        ofpc.Where(t => t.unsafeObservationCount > 0 && t.subCategoryName == c).Sum(
                            t => t.unsafeObservationCount);

                    
                    //Get category percentages
                    

                    var d = new Deficiencies()
                    {
                        Category = c
                    };
                    if (gcunsafes > 0)
                        d.GC = Math.Round((g / gcunsafes) * 100, 3, MidpointRounding.AwayFromZero);
                    if (ofpcunsafes > 0)
                        d.OFPC = Math.Round((o / ofpcunsafes) * 100, 3, MidpointRounding.AwayFromZero);
                    if (rocipunsafes > 0)
                        d.ROCIP = Math.Round((r / rocipunsafes) * 100, 3, MidpointRounding.AwayFromZero);


                    results.GeneralDeficiencies.Add(d);

                }
                //Get A-D severity counts per team
                results.GCSeverityA =
                    gc.Where(t => t.inspectionDate >= start && t.inspectionDate < end).Sum(
                        t => t.severityLifeThreatCount);
                results.GCSeverityB =
                    gc.Where(t => t.inspectionDate >= start && t.inspectionDate < end).Sum(
                        t => t.severityHighCount);
                results.GCSeverityC =
                    gc.Where(t => t.inspectionDate >= start && t.inspectionDate < end).Sum(
                        t => t.severityMediumCount);
                results.GCSeverityD =
                    gc.Where(t => t.inspectionDate >= start && t.inspectionDate < end).Sum(
                        t => t.severityLowCount);

                results.OFPCSeverityA =
                    ofpc.Where(t => t.inspectionDate >= start && t.inspectionDate < end).Sum(
                        t => t.severityLifeThreatCount);
                results.OFPCSeverityB =
                    ofpc.Where(t => t.inspectionDate >= start && t.inspectionDate < end).Sum(
                        t => t.severityHighCount);
                results.OFPCSeverityC =
                    ofpc.Where(t => t.inspectionDate >= start && t.inspectionDate < end).Sum(
                        t => t.severityMediumCount);
                results.OFPCSeverityD =
                    ofpc.Where(t => t.inspectionDate >= start && t.inspectionDate < end).Sum(
                        t => t.severityLowCount);

                results.ROCIPSeverityA =
                    rocip.Where(t => t.inspectionDate >= start && t.inspectionDate < end).Sum(
                        t => t.severityLifeThreatCount);
                results.ROCIPSeverityB =
                    rocip.Where(t => t.inspectionDate >= start && t.inspectionDate < end).Sum(
                        t => t.severityHighCount);
                results.ROCIPSeverityC =
                    rocip.Where(t => t.inspectionDate >= start && t.inspectionDate < end).Sum(
                        t => t.severityMediumCount);
                results.ROCIPSeverityD =
                    rocip.Where(t => t.inspectionDate >= start && t.inspectionDate < end).Sum(
                        t => t.severityLowCount);

                //Get claims for previous month
                results.Claims = SafetyRepo.GetClaims(start, end);


                foreach (var inj in Injuries)
                {
                    var count = results.Claims.Count(t => t.NCCINatureofInjury.Trim() == inj);
                    if (count > 0)
                        results.Injuries.Add(inj, count);

                }


                return results;
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return null;
            }
        }

        public RegionResults GetRegionResults(string region, DateTime start, DateTime end)
        {
            var results = new RegionResults()
                              {
                                  GCProjects = new List<GCProjects>(),
                                  DefeciencyTypes = new Dictionary<string, int>() ,
                                  Claims = new List<Claim>()
                              };
            try
            {
                //first of the previous month to current first of the month
               
                
                var i = SafetyRepo.GetRegionalMonthlyInspections(start, end, region);
                
                var gc =  i.Where(t => t.inspectorLastName.ToUpper().Contains("(GC)")).ToList();
                var rocip = i.Where(t => t.inspectorLastName.ToUpper().Contains("(ROCIP)")).ToList();
                var ofpc = i.Where(t => t.inspectorLastName.ToUpper().Contains("(OFPC)")).ToList();
                ofpc.AddRange(i.Where(t => t.inspectorLastName.ToUpper().Contains("(MDA)")).ToList());
                ofpc.AddRange(i.Where(t => t.inspectorLastName.ToUpper().Contains("(UTSWMC)")).ToList());



                var projects = (from p in gc select p.projectTitle).Distinct().ToList();
                
                foreach (var p in projects)
                {
                    var g = gc.Where(t => t.projectTitle == p).ToList();
                    results.GCProjects.Add(new GCProjects()
                                               {
                                                   Project = p,
                                                   Institute = region,
                                                   Inspections = (from x in g select x.inspectionID).Distinct().Count()
                                               });
                }

                //Get A-D severity counts per team
                results.GCSeverityA = gc.Sum(t => t.severityLifeThreatCount);
                results.GCSeverityB = gc.Sum(t => t.severityHighCount);
                results.GCSeverityC = gc.Sum(t => t.severityMediumCount);
                results.GCSeverityD = gc.Sum(t => t.severityLowCount);
                
                results.OFPCSeverityA = ofpc.Sum(t => t.severityLifeThreatCount);
                results.OFPCSeverityB = ofpc.Sum(t => t.severityHighCount);
                results.OFPCSeverityC = ofpc.Sum(t => t.severityMediumCount);
                results.OFPCSeverityD = ofpc.Sum(t => t.severityLowCount);
                
                results.ROCIPSeverityA = rocip.Sum(t => t.severityLifeThreatCount);
                results.ROCIPSeverityB = rocip.Sum(t => t.severityHighCount);
                results.ROCIPSeverityC = rocip.Sum(t => t.severityMediumCount);
                results.ROCIPSeverityD = rocip.Sum(t => t.severityLowCount);


                var deficiencies = rocip.Where(t => t.unsafeObservationCount == 1).Select(t => t.categoryName).Distinct();

                foreach (var d in deficiencies)
                {
                    var u = rocip.Count(t => t.unsafeObservationCount > 0 && t.categoryName == d);
                    results.DefeciencyTypes.Add(d,u);
                    
                }

                var projectids = (from p in gc select p.projectID).Distinct().ToList();
                var claims = SafetyRepo.GetClaims(start, end);
                foreach (var p in projectids)
                {
                    var c = claims.Where(t => t.SiteLevel1 == p.ToString()).ToList();
                    if (c.Count == 0) continue;
                    ((List<Claim>)results.Claims).AddRange(c);
                    
                }


                return results;
            }catch(Exception ex)
            {
                Log.Error(ex);
                return null;
            }
        }

        public IList<Inspection> GetTestInspections()
        {
            var i =  SafetyRepo.GetMonthlyInspections(new DateTime(2011, 6, 1), new DateTime(2011, 7, 1));
            return i.Where(t => t.inspectorLastName.ToUpper().Contains("(GC)")).ToList();
        }

        public IList<JobHistory> GetJobHistory()
        {
            try
            {
                return SafetyRepo.GetJobHistory();
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return null;
            }
        }

        public IList<Project> GetProjects()
        {
            try
            {
                return SafetyRepo.GetProjects();
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return null;
            }
        }

        public Project GetProjectByName(string name)
        {
            try
            {
                return SafetyRepo.GetProjectByName(name);

            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return new Project();
            }
        }
    }
}